<template>
  <el-row justify="space-between">
    <!-- 搜索栏-->
    <el-col :span="20">
      <el-input
          v-model="productName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="search"
      >
      </el-input>
    </el-col>

    <!-- 搜索按钮 -->
    <el-col :span="2">
      <el-button type="primary" icon="el-icon-search" @click="search" class="search-button">搜索</el-button>
    </el-col>
    <!--新增按钮-->
    <el-col :span="2">
      <el-button type="primary" @click="openAddDialog">
        <el-icon>
          <Plus/>
        </el-icon>
        新增商品
      </el-button>
    </el-col>
  </el-row>

  <MessageBox2 :page-size="pageSize" :current-page="currentPage" :total="total" :table-data="productStore.products"
               :table-title-list="tableTitleList" :loading="loading" :table-title="tableTitle" :batch-mode="batchMode"
               @current-change="currentPageChange" @size-change="pageSizeChange" @selectionChange="updateSelectedRows">
    <template #title-btn>
      <el-button type="primary" @click="toggleBatchMode">
        {{ batchMode ? "取消批量操作" : "批量操作" }}
      </el-button>
      <el-button
          type="danger"
          :disabled="!selectedRows.length"
          @click="handleBatchDelete"
          v-if="batchMode"
      >
        批量删除
      </el-button>
    </template>

    <template v-slot:table-btn>
      <el-table-column label="照片">
        <template #default="{ row }">
          <img
              :src="row.productImg"
              alt="商品照片"
              class="preview-image"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button icon="edit" circle plain type="warning" size="mini" @click="openEditDialog(row)">编辑</el-button>
          <el-button icon="delete" circle plain type="danger" size="mini" @click="deleteProduct(row.productId)">删除
          </el-button>
          <!--生成进货按钮-->
          <el-button plain round
                     type="success"
                     size="mini"
                     @click="handleGeneratePurchase(row.productId)">
            生成进货单
          </el-button>

        </template>
      </el-table-column>
    </template>
  </MessageBox2>

  <!--生成进货单对话框-->
  <el-dialog title="生成进货单" v-model="purchaseDialogVisible" width="30%">
    <el-form :model="purchaseData" label-width="130px">
      <el-form-item label="商品编号">
        <el-input v-model="purchaseData.productId" placeholder="商品编号" disabled></el-input>
      </el-form-item>
      <el-form-item label="补充数量" prop="quantity">
        <el-input-number v-model="purchaseData.quantityOrdered" :min="1" placeholder="请输入补充数量"></el-input-number>
      </el-form-item>
      <el-form-item label="预计到货时间">
        <el-date-picker
            v-model="purchaseData.expectedDeliveryDate"
            type="date"
            placeholder="请选择日期"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="purchaseDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmPurchaseOrder">确认生成</el-button>
    </template>
  </el-dialog>


  <!--新增页面-->
  <el-dialog title="新增商品" v-model="addDialogVisible" width="30%">
    <el-form :model="newProduct" label-width="130px">
      <el-form-item label="商品名称" prop="productName" required>
        <el-input v-model="newProduct.productName" placeholder="请输入商品名称"></el-input>
      </el-form-item>

      <el-form-item label="商品描述" prop="password">
        <el-input v-model="newProduct.description" placeholder="请输入描述" type="textarea" :rows="3"></el-input>
      </el-form-item>

      <el-form-item label="商品照片" prop="productImg">
        <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/common/upload"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="headers"
            :on-error="handlePhotoError"
        >
          <div v-if="newProduct.productImg">
            <img :src="newProduct.productImg" class="el-upload-list__item-thumbnail preview-image"
                 alt=""/>
            <div class="photo-actions">
              <el-button size="mini" type="danger" @click="deletePhoto" icon="el-icon-delete" circle>删除</el-button>
            </div>
          </div>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>

      </el-form-item>
      <el-form-item label="成本价" prop="standardCost" required>
        <el-input-number v-model="newProduct.standardCost" :min="0" placeholder="请输入成本价格"></el-input-number>
      </el-form-item>

      <el-form-item label="售价" prop="price" required>
        <el-input-number v-model="newProduct.price" placeholder="请输入售价"></el-input-number>
      </el-form-item>

      <el-form-item label="正在进货的数量" prop="reorderCount" required>
        <el-input-number v-model="newProduct.reorderCount" :min="0" placeholder="请输入正在进货数量"></el-input-number>
      </el-form-item>


      <el-form-item label="仓库数量" prop="handCount" required>
        <el-input-number v-model="newProduct.handCount" placeholder="请输入仓库拥有数量"></el-input-number>
      </el-form-item>
      <el-form-item label="最低容量" prop="targetCount" required>
        <el-input-number v-model="newProduct.targetCount" placeholder="请输入仓库最少储存数量"></el-input-number>
      </el-form-item>

      <el-form-item label="每单位数量" prop="note">
        <el-input-number v-model="newProduct.quantityPerUnit" placeholder="请输入每单位数量"></el-input-number>
      </el-form-item>
      <el-form-item label="生产日期" prop="produceDate">
        <div class="block">
          <span class="demonstration"></span>
          <el-date-picker
              v-model="newProduct.produceDate"
              type="date"
              placeholder="Pick a day"
              value-format="YYYY-MM-DD"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveProduct">保存</el-button>
    </template>
  </el-dialog>


  <!--修改对话框-->
  <el-dialog title="编辑员工" v-model="editDialogVisible" width="30%">
    <el-form :model="editData" label-width="130px">
      <el-form-item label="商品名称" prop="productName" required>
        <el-input v-model="editData.productName" placeholder="请输入商品名称"></el-input>
      </el-form-item>

      <el-form-item label="商品描述" prop="password">
        <el-input v-model="editData.description" placeholder="请输入描述" type="textarea" :rows="3"></el-input>
      </el-form-item>

      <el-form-item label="商品照片" prop="productImg">
        <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/common/upload"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="headers"
            :on-error="handlePhotoError"
        >
          <div v-if="editData.productImg">
            <img :src="editData.productImg" class="el-upload-list__item-thumbnail preview-image"
                 alt=""/>
            <div class="photo-actions">
              <el-button size="mini" type="danger" @click="deleteEditDataPhoto" icon="el-icon-delete" circle>删除
              </el-button>
            </div>
          </div>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>

      </el-form-item>
      <el-form-item label="成本价" prop="standardCost" required>
        <el-input-number v-model="editData.standardCost" :min="0" placeholder="请输入成本价格"></el-input-number>
      </el-form-item>

      <el-form-item label="售价" prop="price" required>
        <el-input-number v-model="editData.price" placeholder="请输入售价"></el-input-number>
      </el-form-item>

      <el-form-item label="正在进货的数量" prop="reorderCount" required>
        <el-input-number v-model="editData.reorderCount" :min="0" placeholder="请输入正在进货数量"></el-input-number>
      </el-form-item>


      <el-form-item label="仓库数量" prop="handCount" required>
        <el-input-number v-model="editData.handCount" placeholder="请输入仓库拥有数量"></el-input-number>
      </el-form-item>
      <el-form-item label="最低容量" prop="targetCount" required>
        <el-input-number v-model="editData.targetCount" placeholder="请输入仓库最少储存数量"></el-input-number>
      </el-form-item>

      <el-form-item label="每单位数量" prop="note">
        <el-input-number v-model="editData.quantityPerUnit" placeholder="请输入每单位数量"></el-input-number>
      </el-form-item>
      <el-form-item label="生产日期" prop="produceDate">
        <div class="block">
          <span class="demonstration"></span>
          <el-date-picker
              v-model="editData.produceDate"
              type="date"
              placeholder="Pick a day"
              value-format="YYYY-MM-DD"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="editProduct" :loading="isSaving">保存</el-button>
    </template>
  </el-dialog>

</template>

<script setup>
import {reactive, ref, toRaw} from 'vue'
import MessageBox2 from "@/components/MessageBox2.vue";
import {productsStore} from "@/stores/modules/products"
import {addProductService, deleteProductService, getProductPageListService, updateProductService} from "@/api/product"
import {generatePurchaseOrderService} from "@/api/PurchaseOrder.js";
import {ElMessage, ElMessageBox} from "element-plus";

// 获取store 数据
const productStore = productsStore()


// 表格参数
const tableTitle = "仓库商品信息"
const tableTitleList = {
  productId: '商品编号',
  productName: '商品名称',
  description: '商品描述',
  standardCost: '成本价',
  price: '销售价',
  reorderCount: '重新订购存量',
  handCount: '当前库存量',
  targetCount: '最低库存量',
}
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const productName = ref('')

//页面变化 + 条件变化
const getProductPage = async (currentPage, pageSize, productName) => {
  loading.value = true

  console.log(currentPage, pageSize, productName)
  try {
    const res = await getProductPageListService(currentPage.value, pageSize.value, productName.value)
    console.log(res)
    if (res.status === 200) {
      productStore.setProducts(res.data.data.records)
      total.value = res.data.data.total
    }
  } catch (e) {
    ElMessage.error('请求出错')
    console.log(e)
  } finally {
    loading.value = false
  }
}

// 查询函数
const search = () => {
  getProductPage(currentPage, pageSize, productName)
}

//子组件触发
const currentPageChange = (cP) => {
  currentPage.value = cP
  getProductPage(currentPage, pageSize, productName)
}
const pageSizeChange = (size) => {
  pageSize.value = size
  getProductPage(currentPage, pageSize, productName)
}

// 新增产品信息
const addDialogVisible = ref(false)
const newProduct = reactive({
  productName: '',
  description: '',
  productImg: '',
  standardCost: '',
  price: '',
  reorderCount: '',
  handCount: '',
  targetCount: '',
  quantityPerUnit: '',
  produceDate: ''
})

// 新增
const openAddDialog = () => {
  addDialogVisible.value = true
}

const saveProduct = async () => {
  try {
    const res = await addProductService(newProduct)
    console.log(res)
    if (res.status === 200) {
      ElMessage.success('新增客户成功')
      await getProductPage(currentPage, pageSize, productName)
      addDialogVisible.value = false
    } else {
      ElMessage.error('新增失败')
    }
  } catch (e) {
    ElMessage.error('请求出错')
    console.log(e)
  }
}

//编辑产品
const editDialogVisible = ref(false)
const editData = ref({})
const isSaving = ref(false); // 用于保存按钮的加载状态
const openEditDialog = (row) => {
  editData.value = {...row}
  editDialogVisible.value = true
}
const editProduct = async () => {
  try {
    isSaving.value = true;
    const res = await updateProductService(toRaw(editData.value))
    if (res.status === 200) {
      ElMessage.success('编辑客户成功')
      await getProductPage(currentPage, pageSize, productName)
      editDialogVisible.value = false
    } else {
      ElMessage.error('编辑失败')
    }
  } catch (e) {
    ElMessage.error('请求出错')
    console.log(e)
  } finally {
    isSaving.value = false;
  }
}

//删除编辑照片
const deleteEditDataPhoto = () => {
  editData.value.photo = ""
}

// 批量删除客户
// 状态控制
const batchMode = ref(false); // 是否启用批量模式
const selectedRows = ref([]); // 存储选中的行数据
// 切换批量操作模式
const toggleBatchMode = () => {
  batchMode.value = !batchMode.value;
  if (!batchMode.value) {
    selectedRows.value = []; // 清空选中数据
  }
};
// 更新选中的行数据
const updateSelectedRows = (rows) => {
  selectedRows.value = rows;
};
// 批量删除逻辑
const handleBatchDelete = async () => {
  const ids = selectedRows.value.map((row) => row.productId);
  try {
    const res = await deleteProductService(ids);
    if (res.status === 200) {
      productStore.products = productStore.products.filter(
          (item) => !ids.includes(item.productId)
      );
      toggleBatchMode();
    }
  } catch (error) {
    console.error(error);
  }
  await getProductPage(currentPage, pageSize, productName)
};
//单个删除
const deleteProduct = async (id) => {
  const res = await deleteProductService(id)
  if (res.status === 200) {
    productStore.products = productStore.products.filter(item => item.productId !== id)
    ElMessage.success('删除成功')
  }
  await getProductPage(currentPage, pageSize, productName)
}

// 上传照片
const handleAvatarSuccess = (fileUrl) => {
  // console.log(fileUrl)
  newProduct.productImg = fileUrl.data
  editData.value.productImg = fileUrl.data
}

const beforeAvatarUpload = (file) => {
  headers.value.token = localStorage.getItem('token'); // 动态更新令牌
  const isJPG = file.type === 'image/jpeg';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
}
const headers = ref({
  token: localStorage.getItem('token'), // 如果需要 token 验证
});
const deletePhoto = () => {
  newProduct.productImg = ""
}
const handlePhotoError = () => {
  ElMessage.error('上传头像图片失败!');
}

// 生成进货单
// 控制进货单对话框的显示
const purchaseDialogVisible = ref(false);
// 进货单数据
const purchaseData = reactive({
  productId: '',
  quantityOrdered: 0, // 默认补充数量
  orderDate: '',
  expectedDeliveryDate: '',
  purchaseOrderStatus: 0
});
// 打开进货单对话框
const handleGeneratePurchase = (productId) => {
  // 根据商品 ID 从列表中获取商品信息
  purchaseData.productId = productId;
  purchaseDialogVisible.value = true;
};
// 确认生成进货单
const confirmPurchaseOrder = async () => {
  try {
    const res = await generatePurchaseOrderService(toRaw(purchaseData));
    if (res.status === 200) {
      await ElMessageBox.alert('进货单生成成功', '提示', {
        confirmButtonText: '确定',
        type: 'success',
      })
      purchaseDialogVisible.value = false;
      // 可在此处调用接口刷新商品列表
      await getProductPage(currentPage, pageSize, productName);
    } else {
      await ElMessageBox.alert('进货单生成失败', '错误', {
        confirmButtonText: '确定',
        type: 'error',
      })
    }
  } catch (e) {
    console.error(e);
    ElMessage.error('请求出错');
  }
};

// 初始化
console.log("初始化")
getProductPage(currentPage, pageSize, productName)
console.log("初始化结束")

</script>

<style scoped>
.search-button {
  width: 100%;
}

.preview-image {
  width: 100px; /* 设置宽度 */
  height: 100px; /* 设置高度 */
  object-fit: cover; /* 保持图片比例裁剪适配 */
  border-radius: 4px; /* 如果需要圆角 */
}

.photo-container {
  position: relative;
  width: 100px;
  height: 100px;
}

.photo-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  border-radius: 4px;
  cursor: pointer;
}

.photo-preview {
  position: relative;
  width: 100%;
  height: 100%;
}

.photo-actions {
  position: absolute;
  top: 5px;
  right: 5px;
  display: flex;
  gap: 5px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border: #baaeb5 1px dashed;
}
</style>